import C_App from "../../core/C_App";
import { C_NotificationConst } from "../../core/C_NotificationConst";
import C_Hole from "./C_Hole";

const { ccclass, property } = cc._decorator;
/** 面板组件 */
@ccclass
export default class C_Plate extends cc.Component {

    @property({ tooltip: "面板所在层级，越大越上面" })
    protected _curIndex: number = 0;

    @property()
    set curIndex(v) {
        this._curIndex = v;
        if (!CC_EDITOR) {
            this.autoGroup()
        }
    }

    get curIndex() {
        return this._curIndex;
    }

    @property(cc.BoxCollider)
    boxCollision: cc.BoxCollider = null;

    @property(cc.Node)
    boxContent: cc.Node = null;
    protected _isActive: boolean = true;

    content: cc.Node = null;
    set plateActive(isActive: boolean) {
        this._isActive = isActive;
        if (this._plateColliders && this._plateColliders.length) {
            this._plateColliders.forEach(v => {
                v.enabled = isActive;
            })
        }

        if (this._holes) {
            this._holes.forEach(v => {
                v.physicsBox.enabled = isActive;
            })
        }
        if (!this.content) {
            this.content = this.node.parent;
        }
        if (isActive) {
            C_App.NotificationCenter.addListener(C_NotificationConst.OPEN_SCREW, this.onOpenScrew, this);

        }
        else {
            C_App.NotificationCenter.removeListener(C_NotificationConst.OPEN_SCREW, this.onOpenScrew, this);

        }
        if (isActive) {
            this.checkScrew();
        }
        this._boxColliders.forEach(v => {
            v.enabled = isActive;
        })
    }

    protected onDisable(): void {
        C_App.NotificationCenter.removeListener(C_NotificationConst.OPEN_SCREW, this.onOpenScrew, this);

    }

    protected onDestroy(): void {
        C_App.NotificationCenter.removeListener(C_NotificationConst.OPEN_SCREW, this.onOpenScrew, this);

    }

    get plateActive() {
        return this._isActive;
    }

    checkScrew() {
        let cnt = 0;
        this._holes.forEach(v => {
            if (v.hasScrew()) {
                cnt++;
            }
        })
        if (cnt <= 1) {
            this._holes.forEach(hole => {
                if (hole.hasScrew()) {
                    hole.physicsBox.enabled = true;
                    // console.log("dynamic:", this.node.name);
                }
                this.scheduleOnce(() => {
                    if (this._rigidBody)
                        this._rigidBody.type = cc.RigidBodyType.Dynamic
                }, 0)
                // this._holeColliders.push(hole.screwFrame)
            });
            C_App.NotificationCenter.removeListener(C_NotificationConst.OPEN_SCREW, this.onOpenScrew, this);
        }
    }

    removeCom() {
        this.plateActive = false;

        if (this._plateColliders && this._plateColliders.length) {
            this._plateColliders.forEach(v => {
                v.enabled = false;
            })
        }
        // if (this._rigidBody)
        //     this._rigidBody.type = cc.RigidBodyType.Static;

        this.schedule(this.removeBox, .1, cc.macro.REPEAT_FOREVER, 1)
        // const t = Date.now();

        // this._boxColliders.forEach(v => {
        //     v.enabled = false;
        // })
        // console.log("removeCom 1>", Date.now() - t)

        // this.node.destroy();
        // console.log("removeCom 2>", Date.now() - t)

    }

    removeBox() {
        const t = Date.now();

        if (this._boxColliders.length) {
            const box = this._boxColliders.pop();
            box.enabled = false;

        }
        else {
            this.node.removeFromParent()
            this.node.destroy();
            this.unschedule(this.removeBox)
        }
        // console.log("removeCom 1>", Date.now() - t)
    }


    onOpenScrew(hole: C_Hole) {
        this.checkScrew();
    }


    _holes: C_Hole[] = null;
    _rigidBody: cc.RigidBody = null;

    _plateColliders: cc.PhysicsCollider[];
    _holeColliders: cc.PhysicsCollider[] = [];
    _boxColliders: cc.BoxCollider[] = [];
    protected onLoad(): void {
        this._holes = this.getComponentsInChildren(C_Hole);
        this._rigidBody = this.getComponent(cc.RigidBody);
        this._plateColliders = this.getComponents(cc.PhysicsCollider);
        this.plateActive = false;
        if (this._rigidBody)
            this._rigidBody.type = cc.RigidBodyType.Static;
        // cc.tween(this.node)
        //     .delay(1)
        //     .call(() => {
        //         this._rigidBody.type = cc.RigidBodyType.Dynamic;
        //     })
        //     .start()
        // const boxes = this.boxCollision.getComponents(cc.BoxCollider);
        // this.boxCollision.enabled = false;
        // this.boxCollision.node.removeFromParent()

        this.boxContent.children.forEach(v => {
            this._boxColliders.push(v.getComponent(cc.BoxCollider));
        })
        // boxes.forEach(v => {
        //     // if (this._boxColliders.length) {
        //     //     return;
        //     // }
        //     const temp = new cc.Node()//cc.instantiate(v.node);
        //     this.node.addChild(temp);
        //     const box = temp.addComponent(cc.BoxCollider);
        //     // 复制 BoxCollider 属性
        //     box.offset = v.offset.clone();
        //     box.size = v.size.clone();
        //     box.tag = v.tag;
        //     this._boxColliders.push(box);
        // })

        this.autoGroup();
    }

    autoGroup() {
        const temp = this.curIndex % 3;
        const group = temp == 0 ? "default" : temp == 1 ? "group4" : "group5"
        this.node.group = group;
        this.node.name = 'layer_' + this.curIndex + "_" + group
        this.traverseAllChildren(this.node, (v) => {
            v.group = group;
        })
        // this.boxCollision.node.group = 'default';
        if (this._holes)
            this._holes.forEach((hole) => {
                hole.node.group = group;
                hole.curIndex = this.curIndex;
                hole.boxCollision.node.group = 'group5'

                // this._holeColliders.push(hole.screwFrame)
            });
        this._boxColliders.forEach(v => {
            v.node.group = 'group6';
        })
    }

    /**
     * 递归遍历所有子节点（包括嵌套子节点）
     * @param node 起始节点
     * @param callback 遍历时的回调函数
     */
    traverseAllChildren(node: cc.Node, callback: (child: cc.Node) => void) {
        // 遍历当前节点的直接子节点
        node.children.forEach((child) => {
            // 执行回调（例如打印节点名、修改属性等）
            callback(child);
            // 递归遍历子节点的子节点
            this.traverseAllChildren(child, callback);
        });
    }

    checkPos() {
        if (this.node.y < -1000) {
            return true;
        }
    }
}
